//
//  DeviceDelegateHelper.m
//  SURE
//
//  Created by 王玉龙 on 16/11/21.
//  Copyright © 2016年 longlong. All rights reserved.
//


NSString *const CellMessageReadCount = @"CellMessageReadCount";
NSString *const CellMessageUnReadCount = @"CellMessageUnReadCount";

#import "DeviceDelegateHelper.h"

#import "EmojiConvertor.h"
#import "ECRevokeMessageBody.h"
#import <AudioToolbox/AudioToolbox.h>

#import "IMMsgDBAccess.h"

#import "DemoGlobalClass.h"

#import "ECDevice.h"
#import "ChatViewController.h"

@interface DeviceDelegateHelper()
@property(atomic, assign) NSUInteger offlineCount;
@end

@implementation DeviceDelegateHelper

{
    SystemSoundID receiveSound;
}

//第一步：创建单例方法

+(DeviceDelegateHelper*)sharedInstance
{
    static DeviceDelegateHelper *devicedelegatehelper;
    
    static dispatch_once_t devicedelegatehelperonce;
    
    dispatch_once(&devicedelegatehelperonce, ^
    {
        devicedelegatehelper = [[DeviceDelegateHelper alloc] init];
    });
    
    return devicedelegatehelper;
    
}

-(instancetype)init
{
    if (self = [super init])
    {
        
        
        NSBundle *imBundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"CCPSDKBundle" ofType:@"bundle"]];

        NSString *soundPath = [imBundle pathForResource:@"receive_msg" ofType:@"caf"];
        
        
        if (soundPath)
        {
            NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
            OSStatus err = AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL,
                                                            &receiveSound);
            if (err != kAudioServicesNoError)
                NSLog(@"Could not load %@, error code: %d", soundURL, (int)err);
        }
    }
    return self;
}
- (void)dealloc
{
    AudioServicesDisposeSystemSoundID(receiveSound);
}

-(void)playRecMsgSound:(ECMessage*)message
{
    //后台切前台接收消息判断
    if (self.preDate==nil)
    {
        self.preDate = [NSDate date];
    }
    
    if (self.isB2F && self.preDate != nil && [self.preDate timeIntervalSinceNow]>-1)
    {
        self.preDate = [NSDate date];
        return;
    }
    
    self.isB2F = NO;
    
    //是否在会话里接收消息
    BOOL isChat = NO;
    if (self.sessionId.length>0 && message.sessionId.length>0 && [self.sessionId isEqualToString:message.sessionId])
    {
        isChat = YES;
    }
    

    //查看设置
    if ([DemoGlobalClass sharedInstance].isMessageSound && !isChat)
    {
        //播放声音
        AudioServicesPlaySystemSound(receiveSound);
    }

    if ([DemoGlobalClass sharedInstance].isMessageShake)
    {
//        if (self.isChatVC == NO)
//        {
//            [self showAlertWithInfo:message];
//        }
        //震动
        AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
    }
}

- (void)showAlertWithInfo:(ECMessage *)message
{
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:@"您有新的客服消息" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"忽略" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action){}];
    
    UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"查看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
      {
          
        [ChatViewController presentChatViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
      }];
    
    [actionSheet addAction:cancelAction];
    [actionSheet addAction:loginAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:actionSheet animated:YES completion:nil];
}


/**
 @brief 网络改变后调用的代理方法
 @param status 网络状态值
 */
- (void)onReachbilityChanged:(ECNetworkType)status{
    [DemoGlobalClass sharedInstance].netType = status;
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onNetworkChanged object:@(status)];
}


/**
 @brief 系统事件通知
 @param CCPEvents 包含的系统事件
 */
- (void)onSystemEvents:(CCPEvents)events{
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onSystemEvent object:@(events)];
}



#if 0

/**
 @brief 连接状态接口
 @discussion 监听与服务器的连接状态 V4.0版本接口
 @param error 连接的状态
 */
-(void)onConnected:(ECError *)error{
    NSLog(@"\r==========\ronConnected errorcode=%d\r============", (int)error.errorCode);
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:error];
}

#else
/**
 @brief 连接状态接口
 @discussion 监听与服务器的连接状态 V5.0版本接口
 @param state 连接的状态
 @param error 错误原因值
 */

-(void)onConnectState:(ECConnectState)state failed:(ECError*)error {
    switch (state) {
        case State_ConnectSuccess:
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:[ECError errorWithCode:ECErrorType_NoError]];
            break;
        case State_Connecting:
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:[ECError errorWithCode:ECErrorType_Connecting]];
            break;
        case State_ConnectFailed:
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onConnected object:error];
            break;
        default:
            break;
    }
}

#endif


/**
 @brief 个人信息版本号
 @param version 服务器上的个人信息版本号
 */
-(void)onServicePersonVersion:(unsigned long long)version
{
    if ([DemoGlobalClass sharedInstance].dataVersion==0 && version==0)
    {
        [DemoGlobalClass sharedInstance].isNeedSetData = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_needInputName object:nil];
    } else if (version>[DemoGlobalClass sharedInstance].dataVersion)
    {
        [[ECDevice sharedInstance] getPersonInfo:^(ECError *error, ECPersonInfo *person)
        {
            if (error.errorCode == ECErrorType_NoError)
            {
                [DemoGlobalClass sharedInstance].dataVersion = person.version;
                [DemoGlobalClass sharedInstance].birth = person.birth;
                [DemoGlobalClass sharedInstance].nickName = person.nickName;
                [DemoGlobalClass sharedInstance].sex = person.sex;
                [DemoGlobalClass sharedInstance].sign = person.sign;
            }
        }];
    }
}

///**
// @brief 最新软件版本号
// @param version 软件版本号
// @param mode 更新模式  1：手动更新 2：强制更新
// */
//-(void)onSoftVersion:(NSString*)version andUpdateMode:(NSInteger)mode andUpdateDesc:(NSString*)desc{
//    
//    NSLog(@"SoftVersion=%@ mode=%ld",version, (long)mode);
//
//    
//}

-(void)onReceiveDeskMessage:(ECMessage*)message
{
    if (message.from.length==0) {
        return;
    }
    
    if (message.messageBody.messageBodyType == MessageBodyType_Text)
    {
        ECTextMessageBody * textmsg = (ECTextMessageBody *)message.messageBody;
        textmsg.text = [[EmojiConvertor sharedInstance] convertEmojiSoftbankToUnicode:textmsg.text];
    }
    
#warning 时间全部转换成本地时间
    if (message.timestamp) {
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval tmp =[date timeIntervalSince1970]*1000;
        message.timestamp = [NSString stringWithFormat:@"%lld", (long long)tmp];
    }
    
    [[DeviceDBHelper sharedInstance] addNewMessage:message andSessionId:self.sessionId];
    
    [self playRecMsgSound:message];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message];
    
    if(message.messageBody.messageBodyType > MessageBodyType_Text){
        ECFileMessageBody *body = (ECFileMessageBody*)message.messageBody;
        body.displayName = body.remotePath.lastPathComponent;
        [[DeviceChatHelper sharedInstance] downloadMediaMessage:message andCompletion:nil];
    }
}

/**
 @brief 接收即时消息代理函数
 @param message 接收的消息
 */
-(void)onReceiveMessage:(ECMessage*)message
{
    if (message.from.length==0 || message.messageBody.messageBodyType==MessageBodyType_Call) {
        return;
    }
    
    if (message.messageBody.messageBodyType==MessageBodyType_UserState) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"KNOTIFICATION_onUserState" object:message];
        return;
    }
    
    
#warning 时间全部转换成本地时间
    if (message.timestamp)
    {
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval tmp =[date timeIntervalSince1970]*1000;
        message.timestamp = [NSString stringWithFormat:@"%lld", (long long)tmp];
    }
    
    [[DeviceDBHelper sharedInstance] addNewMessage:message andSessionId:self.sessionId];
    
    //同步过来的发送消息不播放提示音
    if (message.messageState == ECMessageState_Receive)
    {
        [self playRecMsgSound:message];
    }
    

    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message];
    
    MessageBodyType bodyType = message.messageBody.messageBodyType;
    if( bodyType == MessageBodyType_Voice || bodyType == MessageBodyType_Video || bodyType == MessageBodyType_File || bodyType == MessageBodyType_Image || bodyType== MessageBodyType_Preview){
        ECFileMessageBody *body = (ECFileMessageBody*)message.messageBody;
        body.displayName = body.remotePath.lastPathComponent;
        
        if (message.messageBody.messageBodyType == MessageBodyType_Video) {
            
            ECVideoMessageBody *videoBody = (ECVideoMessageBody *)message.messageBody;
            
            if (videoBody.thumbnailRemotePath == nil) {
                videoBody.displayName = videoBody.remotePath.lastPathComponent;
                [[DeviceChatHelper sharedInstance] downloadMediaMessage:message andCompletion:nil];
            }
            
        } else {
            [[DeviceChatHelper sharedInstance] downloadMediaMessage:message andCompletion:nil];
        }
    }
}

- (void)onReceiveMessageNotify:(ECMessageNotifyMsg *)message
{
    NSLog(@"onReceiveMessageNotify:--%@",message);
    if (message.messageType == ECMessageNotifyType_DeleteMessage)//删除消息
    {
        ECMessageDeleteNotifyMsg *msg = (ECMessageDeleteNotifyMsg*)message;
        
        [[IMMsgDBAccess sharedInstance] updateMessageLocalPath:msg.messageId withPath:@"" withDownloadState:ECMediaDownloadSuccessed andSession:msg.sender];
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_ReceiveMessageDelete object:nil userInfo:@{@"msgid":msg.messageId, @"sessionid":msg.sender}];
        
    }
    else if (message.messageType == ECMessageNotifyType_RevokeMessage)//撤回消息
    {
        ECMessageRevokeNotifyMsg *msg = (ECMessageRevokeNotifyMsg*)message;
        if ([msg.sender isEqualToString:[DemoGlobalClass sharedInstance].userName])
        {
            return;
        }
        NSString *nickName = [[DemoGlobalClass sharedInstance] getOtherNameWithPhone:msg.sender];
        ECRevokeMessageBody *revokeBody = [[ECRevokeMessageBody alloc] initWithText:[NSString stringWithFormat:@"\"%@\"撤回了一条消息",nickName.length>0?nickName:msg.sender]];
        ECMessage *message = [[ECMessage alloc] initWithReceiver:msg.sessionId body:revokeBody];
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval tmp =[date timeIntervalSince1970]*1000;
        message.timestamp = [NSString stringWithFormat:@"%lld", (long long)tmp];
        message.messageState = ECMessageState_SendSuccess;
        message.from = msg.sender;
        
        if ([[IMMsgDBAccess sharedInstance] getMessagesWithMessageId:msg.messageId OfSession:msg.sessionId]==nil)
        {
            [[DeviceDBHelper sharedInstance] addNewMessage:message andSessionId:msg.sessionId];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message];
        }
        else
        {
            [[DeviceDBHelper sharedInstance] updateSrcMessage:msg.sessionId msgid:msg.messageId withDstMessage:message];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message userInfo:@{@"message":message,@"msgid":msg.messageId, @"sessionid":msg.sessionId}];
        }
    }
    else if (message.messageType == ECMessageNotifyType_MessageIsReaded)//消息已读通知
    {
        ECMessageIsReadedNotifyMsg *isReadMsg = (ECMessageIsReadedNotifyMsg*)message;
        [[IMMsgDBAccess sharedInstance] updateMessageReadState:isReadMsg.sessionId messageId:isReadMsg.messageId isRead:YES];
        NSInteger unreadCount = [[NSUserDefaults standardUserDefaults] integerForKey:[NSString stringWithFormat:@"%@_%@",isReadMsg.messageId,CellMessageUnReadCount]];

        
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_IsReadMessage object:@{@"sessionid":isReadMsg.sessionId,@"messageId":isReadMsg.messageId,@"unreadCount":@(unreadCount)}];
    }
}

/**
 @brief 离线消息数
 @param count 消息数
 */
-(void)onOfflineMessageCount:(NSUInteger)count
{
    NSLog(@"onOfflineMessageCount=%lu",(unsigned long)count);
    self.offlineCount = count;
}

/**
 @brief 需要获取的消息数
 @return 消息数 -1:全部获取 0:不获取
 */
-(NSInteger)onGetOfflineMessage
{
    NSInteger retCount = -1;
    if (self.offlineCount!=0)
    {
        dispatch_async(dispatch_get_main_queue(), ^
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_haveHistoryMessage object:nil];
        });
    }
    return retCount;
}

/**
 @brief 接收离线消息代理函数
 @param message 接收的消息
 */
-(void)onReceiveOfflineMessage:(ECMessage*)message
{
    if (message.from.length==0 || message.messageBody.messageBodyType==MessageBodyType_Call) {
        if (message.messageBody.messageBodyType==MessageBodyType_Call) {
            [[DeviceDBHelper sharedInstance] addNewMessage:message andSessionId:self.sessionId];
            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message];
        }
        return;
    }
    

    
#warning 时间全部转换成本地时间
    if (!message.timestamp)
    {
        NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval tmp =[date timeIntervalSince1970]*1000;
        message.timestamp = [NSString stringWithFormat:@"%lld", (long long)tmp];
    }
    
    [[DeviceDBHelper sharedInstance] addNewMessage:message andSessionId:self.sessionId];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onMesssageChanged object:message];
    
    MessageBodyType bodyType = message.messageBody.messageBodyType;
    if( bodyType == MessageBodyType_Voice || bodyType == MessageBodyType_Video || bodyType == MessageBodyType_File || bodyType == MessageBodyType_Image || bodyType== MessageBodyType_Preview)
    {
        ECFileMessageBody *body = (ECFileMessageBody*)message.messageBody;
        body.displayName = body.remotePath.lastPathComponent;
        
        if (message.messageBody.messageBodyType == MessageBodyType_Video)
        {
            ECVideoMessageBody *videoBody = (ECVideoMessageBody *)message.messageBody;
            if (videoBody.thumbnailRemotePath == nil)
            {
                videoBody.displayName = videoBody.remotePath.lastPathComponent;
                [[DeviceChatHelper sharedInstance] downloadMediaMessage:message andCompletion:nil];
            }
        }
        else
        {
            [[DeviceChatHelper sharedInstance] downloadMediaMessage:message andCompletion:nil];
        }
    }
}

/**
 @brief 离线消息接收是否完成
 @param isCompletion YES:拉取完成 NO:拉取未完成(拉取消息失败)
 */
-(void)onReceiveOfflineCompletion:(BOOL)isCompletion
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_HistoryMessageCompletion object:nil];
    });
    [self playRecMsgSound:nil];
}

/**
 @brief 客户端录音振幅代理函数
 @param amplitude 录音振幅
 */
-(void)onRecordingAmplitude:(double) amplitude{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_onRecordingAmplitude object:@(amplitude)];
}



@end
